package mo_gorm

import (
	"go.uber.org/zap"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"reflect"
	"strconv"
)

func DoFillModelSnowflakeIdBeforeCreate(db *gorm.DB) {
	if db.Statement.Schema == nil {
		return
	}
	for _, field := range db.Statement.Schema.PrimaryFields {
		isAutoIncrement := isFieldAutoIncrement(field)
		if !isAutoIncrement {
			if db.Statement.ReflectValue.Kind() == reflect.Slice {
				for i := 0; i < db.Statement.ReflectValue.Len(); i++ {
					element := db.Statement.ReflectValue.Index(i)
					handleSingleModel(db, field, element)
				}
			} else { //struct
				handleSingleModel(db, field, db.Statement.ReflectValue)
			}
		}
	}
}

func handleSingleModel(db *gorm.DB, field *schema.Field, refVal reflect.Value) {
	value, isZero := field.ValueOf(db.Statement.Context, refVal)
	MoLogger.Debug("DoFillModelSnowflakeIdBeforeCreate", zap.Any("value", value))
	if isZero {
		switch field.DataType {
		case schema.Int, schema.Uint:
			if err := field.Set(db.Statement.Context, refVal, SnowflakeNode.Generate().Int64()); err != nil {
				MoLogger.Warn("DoFillModelSnowflakeIdBeforeCreate:set")
			}
		case schema.String:
			if err := field.Set(db.Statement.Context, refVal, strconv.FormatInt(SnowflakeNode.Generate().Int64(), 10)); err != nil {
				MoLogger.Warn("DoFillModelSnowflakeIdBeforeCreate:set")
			}
		}
	}
}

func isFieldAutoIncrement(field *schema.Field) bool {
	//发现mysql中，没设置成AutoIncrement,但是值也是true
	if !field.AutoIncrement {
		return false
	}
	autoIncrementStr := GetGormTagValByName(field.Tag.Get("gorm"), "autoIncrement")
	if autoIncrementStr == "" || "true" == autoIncrementStr {
		return true
	}
	return false
}
